package com.xbao.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageHelper;
import com.xbao.core.component.page.Pagination;
import com.xbao.core.config.SmsRequest;
import com.xbao.core.config.SmsSender;
import com.xbao.core.util.MyBeanUtil;
import com.xbao.core.util.pub.tool.StringUtils;
import com.xbao.dao.EmpMapper;
import com.xbao.dao.EmpOrgRelMapper;
import com.xbao.dao.EmpRuleMapper;
import com.xbao.model.*;
import com.xbao.model.req.EmpReq;
import com.xbao.model.req.EmpRuleReq;
import com.xbao.model.req.ResultAddition;
import com.xbao.model.vo.EmpVo;
import com.xbao.model.vo.OrgVo;
import com.xbao.service.EmpService;
import com.xbao.service.OrgService;
import com.xbao.service.RoleService;
import com.xbao.wchat.model.WxCommon;
import com.xbao.wchat.service.WxService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 */
@Service
public class EmpServiceImpl implements EmpService {
    @Resource
    private EmpMapper empMapper;
    @Resource
    private RoleService roleService;
    //@Resource
    private WxService wxService;
    @Resource
    private SmsSender smsSender;

    @Autowired
    private EmpRuleMapper ruleMapper;
    @Autowired
    private EmpOrgRelMapper empOrgRelMapper;
    @Resource
    private OrgService orgService;


    @Override
    public void addEmp(EmpReq req) {
        req.setCreatetime(System.currentTimeMillis());
        req.setUpdatetime(System.currentTimeMillis());
        empMapper.insert(req);

        if (req.getRules() != null && req.getRules().size() > 0)
            addEmpRules(req.getId(), req.getOrgid(), req.getRules());
    }

    @Override
    public void deleteEmp(Long id) {
        empMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateEmp(Emp emp) {
        empMapper.updateByPrimaryKey(emp);

    }

    @Override
    public void sendVcode(Emp emp) {
        String vcode = generateSMSCode(emp.getMobile());
        SmsRequest smsRequest = new SmsRequest("", "", "", null);
        HashMap<String, Object> params = new HashMap<>();
        params.put("vcode", vcode);
        SendSmsResponse sendSmsResponse = smsSender.sendSms(smsRequest);
    }

    @Override
    public EmpVo detailEmp(Long id) {
        Emp emp = empMapper.selectByPrimaryKey(id);
        EmpVo vo = MyBeanUtil.copyProperties(emp, EmpVo.class);
        return vo;
    }

    @Override
    public EmpVo detailEmpByOpenId(String openid) {
        EmpExample example = new EmpExample();
        EmpExample.Criteria criteria = example.createCriteria();
        criteria.andWopenidEqualTo(openid);
        List<Emp> vos = empMapper.selectByExample(example);
        if (vos == null || vos.size() != 1)
            return null;
        Emp emp = vos.get(0);
        EmpVo vo = MyBeanUtil.copyProperties(emp, EmpVo.class);
        return vo;
    }

    public void wrapRules(EmpVo vo) {
        if (vo.getId() != null) {
            vo.setRules(roleService.getMyRoles(vo.getId()));
        }
    }


    @Override
    public EmpVo detailOneEmp(EmpReq empReq) {
        Emp emp = empMapper.selectByPrimaryKey(empReq.getId());
        EmpVo vo = MyBeanUtil.copyProperties(emp, EmpVo.class);
        return vo;
    }


    @Override
    public List<EmpVo> queryEmpList(EmpReq empReq) {
        EmpExample empExample = new EmpExample();
        EmpExample.Criteria criteria = empExample.createCriteria();
        if (empReq.getPager() != null) {
            PageHelper.startPage(empReq.getPager().getPageNo(), empReq.getPager().getPageSize());
            empExample.setOrderByClause("id desc");
        }

        if (!StringUtils.isNull(empReq.getName()))
            criteria.andNameLike("%" + empReq.getName() + "%");
        if (empReq.getEmptype() != null) {
            criteria.andEmptypeEqualTo(empReq.getEmptype());
        }
        if (empReq.getOrgid() != null) {
            criteria.andOrgidEqualTo(empReq.getOrgid());
        }
        if (empReq.getCreatetime_start() != null) {
            criteria.andCreatetimeBetween(empReq.getCreatetime_start(), empReq.getCreatetime_end());
        }
        List<Emp> emps = empMapper.selectByExample(empExample);
        List<EmpVo> vos = MyBeanUtil.copyList(emps, EmpVo.class);
        return vos;

    }

    public void resultAdd(List<EmpVo> vos, ResultAddition resultAddition) {
        for (EmpVo vo : vos) {
            if (resultAddition.getIrules()) {
                getEmpRules(vo.getId());

            }

        }
    }

    public void selectDefaultRel(EmpOrgRel rel) {
        rel.setMainflag(1);
        empOrgRelMapper.updateByPrimaryKeySelective(rel);

    }


    @Override
    public void setEmpRule(List<EmpRule> rule) {
        //TODO

    }

    @Override
    public List<Rule> getEmpRules(Long eid) {
        EmpRuleReq req = new EmpRuleReq();
        List<EmpRule> vos = null;
        List<Rule> rules = new ArrayList<Rule>();
        for (EmpRule vo : vos) {
            Rule rule = roleService.detailRUle(vo.getRuleid());
            rules.add(rule);
        }
        return rules;
    }

    @Override
    public void updatePwd(EmpReq empReq) {
        Emp emp = new Emp();
        emp.setId(empReq.getId());
        emp.setPwd(empReq.getNewpwd());
        EmpExample empExample = new EmpExample();
        empExample.createCriteria().andIdEqualTo(emp.getId());
        empMapper.updateByExampleSelective(emp, empExample);

    }

    @Override
    public Integer noPeriodEmpCount(Long time) {
        //TODO
        return null;
    }

    @Override
    public Pagination<EmpVo> noPeriodEmps(Long time) {
        return null;
    }

    @Override
    public Integer countEmpsFOfOrg(Long orgid) {
        EmpExample empExample = new EmpExample();
        empExample.createCriteria().andOrgidEqualTo(orgid);
        return empMapper.countByExample(empExample);
    }

    @Override
    public void addEmpRules(List<EmpRule> rules) {
        for (EmpRule rule : rules) {
            ruleMapper.insert(rule);
        }

    }

    public void addEmpRules(Long eid, Long orgid, List<Rule> rules) {
        List<EmpRule> empRules = new ArrayList<EmpRule>();
        for (Rule rule : rules) {
            EmpRule empRule = new EmpRule();
            empRule.setRuleid(rule.getId());
            empRule.setOrgid(orgid);
            empRules.add(empRule);
        }
        addEmpRules(empRules);
    }


    @Override
    public EmpVo detailEmpBySkey(String skey) {
        EmpExample example = new EmpExample();
        List<Emp> emps = empMapper.selectByExample(example);
        Emp emp = null;
        if (emps != null && !emps.isEmpty())
            emp = emps.get(0);
        EmpVo vo = MyBeanUtil.copyProperties(emp, EmpVo.class);
        return null;
    }

    @Override
    public EmpVo updateEmpByWxCommon(WxCommon wxCommon) {
        EmpVo vo = detailEmpByOpenId(wxCommon.getOpenid());
        EmpReq req = new EmpReq();
        req.setWopenid(wxCommon.getOpenid());
        //req.setWskey(wxCommon.getSkey());
        req.setWunionid(wxCommon.getUnionId());
        if (vo == null) {
            empMapper.updateByPrimaryKeySelective(req);
        } else {
            empMapper.insert(req);
        }
        return vo;

    }

    @Override
    public void addEmpByWxCommon(WxCommon wxCommon) {

    }

    @Override
    public List<OrgVo> getOrgsOfEmp(Long eid) {
        EmpOrgRelExample example = new EmpOrgRelExample();
        EmpOrgRelExample.Criteria criteria = example.createCriteria();
        criteria.andEidEqualTo(eid);
        List<EmpOrgRel> rels = empOrgRelMapper.selectByExample(example);
        List<OrgVo> vos = new ArrayList<>();
        for (EmpOrgRel rel : rels) {
            OrgVo vo = orgService.detailOrg(rel.getOid());
            vos.add(vo);

        }
        return vos;


    }


    @Override
    public EmpVo loginByThrid(EmpReq empReq) {
        EmpVo vo = null;
        if (empReq.getWcode() != null) {
            WxCommon temp = wxService.getAccessToken(empReq.getWcode());
            WxCommon common=wxService.requestWxInfo(temp.getAccess_token(),temp.getOpenid());
            // common.setSkey(Md5Encryption.GetMD5Code(common.getSession_key() + "," + common.getOpenid()));
            vo = updateEmpByWxCommon(common);
            // empReq.setWskey(common.getSkey());
        }
        return vo;

    }

    public void checkMobileVcode(String mobile, String vcode) {

    }

    @Override
    public EmpVo loginByMobile(EmpReq empReq) {
        Boolean isBind = false;
        checkMobileVcode(empReq.getMobile(), empReq.getVcode());
        if (empReq.getId() != null)
            isBind = true;
        if (isBind) {
            Emp emp = new Emp();
            emp.setId(empReq.getId());
            emp.setMobile(empReq.getMobile());
            updateEmp(emp);
        } else {
            Emp emp = new Emp();
            emp.setMobile(empReq.getMobile());
            //addEmp(emp);
            empReq.setId(emp.getId());

        }
        EmpVo vo = detailEmp(empReq.getId());
        return vo;
    }


    private String generateSMSCode(String mobile) {
        return RandomStringUtils.randomNumeric(4);
    }


}
